import { createElement } from './utils';
import type { ApiConfigItem } from '../types/config';

const modalMaskStyle = `
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.3);
  z-index: 20000;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
`;
const modalBoxStyle = `
  background: #fff;
  border-radius: 12px;
  width: 400px;
  max-width: 96vw;
  box-shadow: 0 10px 30px rgba(0,0,0,0.25), 0 4px 8px rgba(0,0,0,0.12);
  padding: 24px 20px 16px 20px;
  display: flex;
  flex-direction: column;
  transform: scale(0.95);
  opacity: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
`;
const modalTitleStyle = `
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
`;
const modalFooterStyle = `
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 18px;
`;
const inputStyle = `
  width: 100%;
  padding: 6px 8px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  margin-bottom: 12px;
  font-size: 15px;
  transition: border-color 0.2s ease;
  outline: none;
  &:focus {
    border-color: #2563eb;
    box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.1);
  }
`;
const labelStyle = `
  font-size: 14px;
  color: #444;
  margin-bottom: 2px;
  display: block;
`;
const smallBtnStyle = `
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 6px 14px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  &:hover {
    background: #1d4ed8;
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(37, 99, 235, 0.2);
  }
  &:active {
    transform: translateY(0);
  }
`;
const cancelBtnStyle = `
  background: #e5e7eb;
  color: #333;
  border: none;
  border-radius: 6px;
  padding: 6px 14px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  &:hover {
    background: #d1d5db;
    transform: translateY(-1px);
  }
  &:active {
    transform: translateY(0);
  }
`;

const headerItemStyle = `
  display: grid;
  grid-template-columns: minmax(100px, 1fr) minmax(100px, 1fr) auto auto;
  gap: 8px;
  padding: 8px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  align-items: center;
  transition: all 0.3s ease;
  position: relative;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 4px;
    height: 100%;
    background-color: #059669;
    border-radius: 4px 0 0 4px;
  }
`;

const disabledHeaderStyle = `
  ${headerItemStyle}
  opacity: 0.5;
  background-color: #f3f4f6;
  &::before {
    background-color: #9ca3af;
  }
`;

const toggleButtonStyle = `
  ${smallBtnStyle}
  background: #059669;
  &:hover {
    background: #047857;
  }
`;

/*const gearBtnStyle = `
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 50%;
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  font-size: 28px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  &:hover {
    transform: rotate(45deg) scale(1.1);
    background: #1d4ed8;
    box-shadow: 0 6px 12px rgba(0,0,0,0.15);
  }
  &:active {
    transform: rotate(45deg) scale(1.05);
  }
`;*/

export function showApiConfigModal(options: {
  mode: 'add' | 'edit',
  data?: ApiConfigItem,
  onSubmit: (item: ApiConfigItem) => void,
  onCancel?: () => void,
}) {
  const { mode, data, onSubmit, onCancel } = options;
  // 深拷贝，避免直接修改原数据
  let form: ApiConfigItem = data ? JSON.parse(JSON.stringify(data)) : {
    target: '',
    replacement: '',
    headers: {},
    enabled: true,
    params: {},
    body: '',
  };

  // 创建遮罩和弹窗
  const mask = createElement('div', { attrs: { style: modalMaskStyle } });
  const box = createElement('div', { attrs: { style: modalBoxStyle } });
  mask.appendChild(box);

  // 添加动画效果
  requestAnimationFrame(() => {
    mask.style.opacity = '1';
    box.style.transform = 'scale(1)';
    box.style.opacity = '1';
  });

  // 关闭弹窗的函数
  const closeModal = (callback?: () => void) => {
    mask.style.opacity = '0';
    box.style.transform = 'scale(0.95)';
    box.style.opacity = '0';
    setTimeout(() => {
      document.body.removeChild(mask);
      callback?.();
    }, 300);
  };

  // 标题
  const title = createElement('div', { attrs: { style: modalTitleStyle } });
  title.textContent = mode === 'add' ? '添加接口映射' : '编辑接口映射';
  box.appendChild(title);

  // 目标接口
  const targetLabel = createElement('label', { attrs: { style: labelStyle } });
  targetLabel.textContent = '目标接口地址';
  const targetInput = createElement('input', { attrs: { style: inputStyle, value: form.target, placeholder: '如 https://api.xxx.com/user' } });
  targetInput.addEventListener('input', () => { form.target = targetInput.value; });
  box.appendChild(targetLabel);
  box.appendChild(targetInput);

  // 替换接口
  const repLabel = createElement('label', { attrs: { style: labelStyle } });
  repLabel.textContent = '替换接口地址';
  const repInput = createElement('input', { attrs: { style: inputStyle, value: form.replacement, placeholder: '如 http://127.0.0.1:3000/mock/user' } });
  repInput.addEventListener('input', () => { form.replacement = repInput.value; });
  box.appendChild(repLabel);
  box.appendChild(repInput);

  // 启用
  const enableWrap = createElement('div', { attrs: { style: 'margin-bottom:12px;' } });
  const enableInput = createElement('input', { attrs: { type: 'checkbox', style: 'margin-right:6px;' } });
  enableInput.checked = !!form.enabled;
  enableInput.addEventListener('change', () => { form.enabled = enableInput.checked; });
  enableWrap.appendChild(enableInput);
  enableWrap.appendChild(document.createTextNode('启用此映射'));
  box.appendChild(enableWrap);

  // params
  const paramsLabel = createElement('label', { attrs: { style: labelStyle } });
  paramsLabel.textContent = '请求参数（params，键值对）';
  box.appendChild(paramsLabel);
  const paramsList = createElement('div');
  function renderParams() {
    paramsList.innerHTML = '';
    Object.entries(form.params || {}).forEach(([k, v]) => {
      const row = createElement('div', { attrs: { style: 'display:flex;gap:4px;margin-bottom:4px;' } });
      const keyInput = createElement('input', { attrs: { style: 'flex:1 1 0%;' + inputStyle, value: k, placeholder: '参数名' } });
      const valInput = createElement('input', { attrs: { style: 'flex:1 1 0%;' + inputStyle, value: v, placeholder: '值' } });
      const delBtn = createElement('button', { attrs: { style: cancelBtnStyle } });
      delBtn.textContent = '删除';
      delBtn.addEventListener('click', () => {
        if (form.params) delete form.params[k];
        renderParams();
      });
      keyInput.addEventListener('input', () => {
        if (form.params) {
          if (keyInput.value !== k) {
            delete form.params[k];
          }
          form.params[keyInput.value] = valInput.value;
        }
        renderParams();
      });
      valInput.addEventListener('input', () => {
        if (form.params) form.params[keyInput.value] = valInput.value;
      });
      row.appendChild(keyInput);
      row.appendChild(valInput);
      row.appendChild(delBtn);
      paramsList.appendChild(row);
    });
    // 添加按钮
    const addBtn = createElement('button', { attrs: { style: smallBtnStyle } });
    addBtn.textContent = '添加参数';
    addBtn.addEventListener('click', () => {
      if (!form.params) form.params = {};
      form.params[''] = '';
      renderParams();
    });
    paramsList.appendChild(addBtn);
  }
  renderParams();
  box.appendChild(paramsList);

  // headers
  const headersLabel = createElement('label', { attrs: { style: labelStyle } });
  headersLabel.textContent = '请求头（headers，键值对）';
  box.appendChild(headersLabel);
  const headersList = createElement('div', { attrs: { style: 'display:flex;flex-direction:column;gap:12px;' } });
  function renderHeaders() {
    headersList.innerHTML = '';
    Object.entries(form.headers || {}).forEach(([k, v]) => {
      const row = createElement('div', { 
        attrs: { 
          style: v.enabled ? headerItemStyle : disabledHeaderStyle 
        } 
      });
      
      const keyInput = createElement('input', { 
        attrs: { 
          style: inputStyle, 
          value: k, 
          placeholder: 'Header名',
          disabled: !v.enabled ? 'disabled' : ''
        } 
      });
      
      const valInput = createElement('input', { 
        attrs: { 
          style: inputStyle, 
          value: v.value, 
          placeholder: '值',
          disabled: !v.enabled ? 'disabled' : ''
        } 
      });

      const toggleBtn = createElement('button', { 
        attrs: { 
          style: toggleButtonStyle,
          title: v.enabled ? '禁用' : '启用'
        } 
      });
      toggleBtn.textContent = v.enabled ? '禁用' : '启用';
      
      const delBtn = createElement('button', { 
        attrs: { 
          style: cancelBtnStyle,
          title: '删除'
        } 
      });
      delBtn.textContent = '删除';

      // 监听启用/禁用按钮
      toggleBtn.addEventListener('click', () => {
        if (form.headers) {
          form.headers[k].enabled = !form.headers[k].enabled;
          renderHeaders();
        }
      });

      // 监听删除按钮
      delBtn.addEventListener('click', () => {
        if (form.headers) delete form.headers[k];
        renderHeaders();
      });

      // 监听输入变化
      keyInput.addEventListener('input', () => {
        if (form.headers) {
          if (keyInput.value !== k) {
            const enabled = form.headers[k].enabled;
            delete form.headers[k];
            form.headers[keyInput.value] = { 
              value: valInput.value, 
              enabled 
            };
          }
        }
      });

      valInput.addEventListener('input', () => {
        if (form.headers) {
          form.headers[keyInput.value] = { 
            value: valInput.value, 
            enabled: form.headers[keyInput.value]?.enabled ?? true 
          };
        }
      });

      row.appendChild(keyInput);
      row.appendChild(valInput);
      row.appendChild(toggleBtn);
      row.appendChild(delBtn);
      headersList.appendChild(row);
    });

    // 添加按钮
    const addBtn = createElement('button', { attrs: { style: smallBtnStyle } });
    addBtn.textContent = '添加Header';
    addBtn.addEventListener('click', () => {
      if (!form.headers) form.headers = {};
      form.headers[''] = { value: '', enabled: true };
      renderHeaders();
    });
    headersList.appendChild(addBtn);
  }
  renderHeaders();
  box.appendChild(headersList);

  // body
  const bodyLabel = createElement('label', { attrs: { style: labelStyle } });
  bodyLabel.textContent = '请求体（body，可选）';
  const bodyInput = createElement('textarea', { attrs: { style: inputStyle + 'min-height:60px;', placeholder: '如 {"mock":true}' } });
  bodyInput.value = form.body || '';
  bodyInput.addEventListener('input', () => { form.body = bodyInput.value; });
  box.appendChild(bodyLabel);
  box.appendChild(bodyInput);

  // 底部按钮
  const footer = createElement('div', { attrs: { style: modalFooterStyle } });
  const cancelBtn = createElement('button', { attrs: { style: cancelBtnStyle } });
  cancelBtn.textContent = '取消';
  cancelBtn.addEventListener('click', () => {
    closeModal(onCancel);
  });
  const okBtn = createElement('button', { attrs: { style: smallBtnStyle } });
  okBtn.textContent = '确定';
  okBtn.addEventListener('click', () => {
    // 校验
    if (!form.target.trim() || !form.replacement.trim()) {
      alert('目标接口和替换接口不能为空');
      return;
    }
    closeModal(() => onSubmit(form));
  });
  footer.appendChild(cancelBtn);
  footer.appendChild(okBtn);
  box.appendChild(footer);

  document.body.appendChild(mask);
} 